import { createRouter, createWebHashHistory } from 'vue-router'
import { constantRoute } from './routes'
import pinia from '@/store';
import useUserStore from '@/store/modules/user';
import setting from '@/setting';
import { timeStampTransformstring } from '@/utils/plugins'

const userStore = useUserStore(pinia)

const router = createRouter({
  history: createWebHashHistory(),
  routes: constantRoute,
  scrollBehavior() {
    return {
      left: 0,
      top: 0
    }
  }
})

// 白名单
const whiteList = ['/login', '/404']

router.beforeEach((to: any, from: any, next: any) => {
  document.title = `${setting.title} - ${to.meta.title}`
  const token = sessionStorage.getItem('token')
  if (!token) {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  } else {
    if (to.path == '/login') {
      next({ path: '/' })
    } else {
      next()
    }
  }
})

router.afterEach((to) => {
  const token = sessionStorage.getItem('token')
  if (token) {
    if (!userStore.username) {
      // 获取用户信息
      userStore.userInfo({ token: sessionStorage.getItem('token') })
    }
    if (to.path == '/' || to.path == '/login') {
      (window as any).updateWaterMark({ text: '' })
    } else {
      const flag = useUserStore().flag
      if (flag && flag == true) {
        const _text = `${userStore.username}-${setting.title}-${timeStampTransformstring(Date.now())}` as string
        (window as any).updateWaterMark({ text: _text })
      } else {
        const _text = '' as string
        (window as any).updateWaterMark({ text: _text })
      }
    }
  }
})



export default router